<template>
  <div class="rating-selector">
    <div class="button-group">
      <div
        v-for="option in ratingOptions"
        :key="option.value"
        class="rating-button"
        :class="{ active: selectedRating === option.value }"
        @click="selectRating(option.value)"
      >
        {{ option.text }}
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, computed } from 'vue';

const props = defineProps({
  modelValue: {
    type: Number,
    default: 0
  },
  maxStars: {
    type: Number,
    default: 5
  },
  step: {
    type: Number,
    default: 0.5,
    validator: value => [0.5, 1].includes(value)
  }
});

const emit = defineEmits(['update:modelValue']);

// 生成评分选项
const ratingOptions = computed(() => {
  const options = [];
  const steps = Math.floor(props.maxStars / props.step);
  
  for (let i = 0; i <= steps; i++) {
    const value = i * props.step;
    options.push({
      value: value,
      text: `${value}`
    });
  }
  
  return options;
});

// 选中的评分
const selectedRating = ref(props.modelValue);

// 选择评分
const selectRating = (value) => {
  selectedRating.value = value;
  emit('update:modelValue', value);
};

// 监听外部变化
watch(() => props.modelValue, (newVal) => {
  selectedRating.value = newVal;
});
</script>

<style scoped lang="less">
.rating-selector {
  display: inline-block;
}

.button-group {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.rating-button {
  padding: 4px 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: #fff;
  cursor: pointer;
  transition: all 0.2s;
  
  &:hover {
    border-color: #409EFF;
    color: #409EFF;
  }
  
  &.active {
    background-color: #409EFF;
    color: white;
    border-color: #409EFF;
  }
}
</style>
